package com.zhanghu.backendZray.utils.AI;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class QwenApiStreamExample {

    /**
     * 设置stream 为true 并没有流式返回效果，那还不如直接用它现成的api
     * @param args
     */
    public static void main(String[] args) {
        try {
            // 设置 API 的请求 URL
            URL url = new URL("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");

            // 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 允许向服务器发送数据
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer ------"); // 替换为你的 API Key

            // 构建请求体
            String requestBody = "{\n" +
                    "    \"model\": \"qwen-turbo-latest\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"system\",\n" +
                    "            \"content\": \"You are a helpful assistant.\"\n" +
                    "        {\n" +
                    "        },\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"写一篇200字的小作文，主题是：中国房价的变迁\"\n" +
                    "        }\n" +
                    "    ],\n" +
                    "    \"stream \": true\n" +
                    "}";

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    // 处理流式返回的数据
                    System.err.println(responseLine);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
